import { commands } from '../../command';
import { CommandConst } from '../../constant';
import { ListDataProvider } from '../../interface';
import { quickActionModeRegister } from '../../quick-action-mode-register';
import { DefaultModeDataItemProvider } from '../default-mode-data-item-provider/default-mode-data-item-provider';

/**
 * 操作栏默认模式数据适配器
 *
 * @author chitanda
 * @date 2022-06-28 18:06:54
 * @export
 * @class DefaultModeDataProvider
 * @implements {ListDataProvider<DefaultModeDataItemProvider>}
 */
export class DefaultModeDataProvider implements ListDataProvider<DefaultModeDataItemProvider> {
  /**
   * 列表行内点击指令
   *
   * @author chitanda
   * @date 2022-06-30 11:06:49
   * @type {string}
   */
  command: string = CommandConst.DEFAULT_MODE_CLICK;

  placeholder: string = '请输入想要搜索的内容';

  list: DefaultModeDataItemProvider[] = [];

  /**
   * 搜索过滤值
   *
   * @author zhanghengfeng
   * @date 2023-07-12 09:07:04
   * @type {string}
   */
  searchVal: string = '';

  constructor() {
    // 注册列表行内点击指令
    commands.register(
      CommandConst.DEFAULT_MODE_CLICK,
      async (data: DefaultModeDataItemProvider) => {
        const { opts } = data.$mode;
        const { keyboards, command, provider } = opts;
        if (this.searchVal) {
          const command = provider?.command;
          if (command) {
            commands.execute(command, data);
          }
          return;
        }
        if (command) {
          if (opts.args) {
            commands.execute(command, ...opts.args);
          } else {
            commands.execute(command);
          }
        } else {
          Mousetrap.trigger(keyboards instanceof Array ? keyboards[0] : keyboards);
        }
      },
      {
        id: CommandConst.DEFAULT_MODE_CLICK,
        title: '默认模式点击',
      },
    );
  }

  /**
   * 过滤展示列表
   *
   * @author chitanda
   * @date 2022-06-29 14:06:49
   * @param {string} [searchVal]
   * @return {*}  {Promise<DefaultModeDataItemProvider[]>}
   */
  async getItems(searchVal?: string): Promise<DefaultModeDataItemProvider[]> {
    this.searchVal = searchVal;
    const modes = quickActionModeRegister.getModes();
    this.list = [];
    if (searchVal) {
      for (let i = 0; i < modes.length; i++) {
        const mode = modes[i];
        if (mode.isDefault) {
          continue;
        }
        const items = await mode.opts.provider?.getItems(searchVal);
        if (Array.isArray(items)) {
          this.list.push(
            ...items.map(item => {
              Object.defineProperty(item, '$mode', {
                value: mode,
              });
              return item as DefaultModeDataItemProvider;
            }),
          );
        }
      }
      return this.list;
    }
    for (let i = 0; i < modes.length; i++) {
      const mode = modes[i];
      if (mode.isDefault) {
        continue;
      }
      this.list.push(new DefaultModeDataItemProvider(i.toString(), mode));
    }
    return this.list;
  }
}
